/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.chart.utils;

import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import org.seppiko.chart.exceptions.SeppikoProcessorException;
import org.seppiko.chart.utils.logging.LoggingManager;
import org.seppiko.commons.utils.http.HttpClientException;
import org.seppiko.commons.utils.http.HttpClientUtil;
import org.seppiko.commons.utils.http.HttpMethod;

/**
 * Http Client Util with java.net.http
 *
 * @author Leonard Woo
 */
public class HttpClientUtils {

  private static final LoggingManager logger = LoggingManager.getInstance().getLogger(
      HttpClientUtils.class.getName());

  public static byte[] downloadGet(String url) {
    try {
      return clientWithByteArray(url, HttpMethod.GET, 5, null, null);
    } catch (URISyntaxException | SeppikoProcessorException ex) {
      logger.warn("Get request failed", ex);
    } catch (HttpClientException ex) {
      logger.warn("Get response failed", ex);
    }
    return null;
  }

  public static byte[] clientWithByteArray (String url, HttpMethod method, int timeout,
      LinkedHashMap<String, ArrayList<String>> headers, String requestBody)
      throws URISyntaxException, HttpClientException, SeppikoProcessorException {
    HttpRequest req = HttpClientUtil.getRequest(url, method, timeout, headers, requestBody);
    if (req == null) {
      throw new SeppikoProcessorException();
    }
    HttpResponse<byte[]> resp = HttpClientUtil.getResponseByteArray(req, null);
    if (resp == null) {
      throw new HttpClientException();
    }
    return resp.body();
  }
}
